package com.sqx.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.*;
import com.sqx.modules.goods.service.*;
import com.sqx.modules.goods.utils.SkuUtil;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.shop.dao.ShopMessageDao;
import com.sqx.modules.sys.dao.SysUserRoleDao;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private GoodsAttrService goodsAttrService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private GoodsAttrValueService goodsAttrValueService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private ShopMessageDao shopMessageDao;
    @Autowired
    private TbIndentService tbIndentService;

    @Transactional
    @Override
    public Result insertGoods(Goods goods) {
        //判断商户保证金是否足够
        CommonInfo one = commonInfoService.findOne(270);
        GoodsShop goodsShop = shopMessageDao.selectOne(new QueryWrapper<GoodsShop>().eq("shop_id", goods.getShopId()));
        if(goodsShop.getCashDeposit().doubleValue()<Double.valueOf(one.getValue())){
            return Result.error("您的保证金不足，请交保证金后再发布商品！");
        }
        //添加商品信息
        goods.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goods.setStatus(0);
        goods.setSalesVolume(0);
        goodsDao.insert(goods);

        GoodsShopRelevancy goodsShopRelevancy = new GoodsShopRelevancy();
        goodsShopRelevancy.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goodsShopRelevancy.setGoodsId(goods.getGoodsId());
        goodsShopRelevancy.setInventory(0);
        goodsShopRelevancy.setStatus(0);
        goodsShopRelevancy.setShopId(goods.getShopId());
        goodsShopRelevancy.setSales(0);
        goodsShopDao.addGoodsShopRelevancy(goodsShopRelevancy);

        //添加规格信息
        if(goods.getAttr().size()>0){
            List<GoodsAttr> attr = goods.getAttr();
            for (GoodsAttr a : attr) {
                a.setGoodsId(goods.getGoodsId());
                goodsAttrService.saveGoodsAttr(a);
            }
        }
        List<GoodsSku> sku = goods.getSku();
        for (GoodsSku v : sku) {
            v.setGoodsId(goods.getGoodsId());
            goodsSkuService.save(v);
        }
        return Result.success();


        /*//添加规格信息
        List<GoodsSku> goodsSkuList = goods.getGoodsSkuList();
        get(goodsSkuList, 0L, goods.getGoodsId());
        return Result.success();*/
    }

    /*public void get(List<GoodsSku> goodsSkuList, Long parentId, Long goodsId){
        for(int i = 0;i<goodsSkuList.size();i++){
            GoodsSku goodsSku = goodsSkuList.get(i);
            goodsSku.setParentId(parentId);
            goodsSku.setGoodsId(goodsSku.getGoodsId());
            goodsSku.setGoodsId(goodsId);
            goodsSkuDao.insertGoodsSku(goodsSku);
            if(goodsSku.getGoodsSkuList().size()>0){
                get(goodsSku.getGoodsSkuList(), goodsSku.getSkuId(), goodsId);
            }
        }
    }*/


    @Override
    public Result selectGoodsList(Long shopId, Double lng, Double lat) {
        GoodsShop goodsShop = goodsShopDao.selectGoodsList(shopId, lng, lat);
        List<Goods> goodsList = goodsDao.selectGoodsClassifyList(shopId);
        ArrayList list = new ArrayList();
        for(int i = 0;i<goodsList.size();i++){
            HashMap hashMap = new HashMap();
            GoodsClassify goodsClassify = goodsDao.selectClassify(goodsList.get(i).getClassifyId());
            if(goodsClassify!=null){
                List<Goods> goodsList1 = goodsDao.selectGoodsByClassify(goodsList.get(i).getClassifyId(), shopId);
                hashMap.put("classifyId", goodsList.get(i).getClassifyId());
                hashMap.put("classifyName", goodsClassify.getClassifyName());
                hashMap.put("goodsList", goodsList1);
                list.add(hashMap);
            }
        }
        CommonInfo one = commonInfoService.findOne(292);
        CommonInfo one1 = commonInfoService.findOne(293);
        if(goodsShop.getDistance()==null){
            goodsShop.setDistance(0.00);
        }
        Double a = goodsShop.getDistance()/Double.valueOf(one.getValue());
        if(a<Double.valueOf(one1.getValue())){
            a=Double.valueOf(one1.getValue());
        }
        goodsShop.setErrandTime(a);
        HashMap hashMap = new HashMap();
        hashMap.put("goodsShop", goodsShop);
        hashMap.put("list", list);
        return Result.success().put("data", hashMap);
    }

    @Transactional
    @Override
    public Result updateGoods(Goods goods) {
        //1.修改attr
        if (goods.getAttr() != null && goods.getAttr().size() > 0) {
            GoodsAttr attr = goods.getAttr().get(goods.getAttr().size()-1);
            attr.setGoodsId(goods.getGoodsId());
            goodsAttrService.updateGoodsAttr(attr);
        } else { //修改为单规格，删除所有attr
            goodsAttrService.deleteAttrAndValue(goods.getGoodsId());
        }
        //2.修改所有sku
        goodsSkuService.deleteGoodsSkuByGoodsId(goods.getGoodsId());
        List<GoodsSku> sku = goods.getSku();
        if(sku!=null){
            for (GoodsSku goodsSku : sku) {
                goodsSku.setGoodsId(goods.getGoodsId());
                goodsSkuService.save(goodsSku);
            }
        }
        goodsDao.updateById(goods);
        return Result.success();
    }

    @Transactional
    @Override
    public Result isFormatAttr(GoodsAttr goodsAttr, String coverImg, String originalPrice, String price) {
        //1.获取商品规格值
        List<GoodsAttrValue> attr = goodsAttr.getAttrValue();
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        //3.sku规格处理集合
        List<List<String>> skuInputList = new ArrayList<>();
        //4.循环规格值
        for (int i = 0; i < attrSize; i++) {
            //5.放入表头数据
            header.add(attr.get(i).getValue());
            //6.sku规格计算
            String detail = attr.get(i).getDetail();
            String[] split = detail.split(",");
            List<String> skuList = new ArrayList<>();
            for (int j = 0; j < split.length; j++) {
                skuList.add(split[j]);
            }
            skuInputList.add(skuList);
        }
        //8.sku规格种类
        List<List<String>> skuList = SkuUtil.skuSort(skuInputList); //计算规格种类
        for (int i = 0; i < skuList.size(); i++) {
            Map<String, Object> sku = new HashMap<>();
            List<String> strings = skuList.get(i);
            String[] arr = strings.toArray(new String[strings.size()]);
            String json = "";
            for (int j = 0; j < attrSize; j++) {
                String arrString = arr[j];
                sku.put("value"+j, arrString);
                json += arrString+",";
            }
            json = json.substring(0, json.length()-1);
            sku.put("json", json);
            sku.put("detailJson", json);
            sku.put("skuImg", coverImg);
            sku.put("skuOriginalPrice", originalPrice);
            sku.put("skuPrice", price);
        //    sku.put("stock", 999);
        //    sku.put("sales", 0);
            value.add(sku);
        }
        //表头
        header.add("图片");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPrice)){
            header.add("原价");
        }
        header.add("售价");
      //  header.add("库存");
     //   header.add("销量");
        header.add("操作");
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data",map);
    }

    @Transactional
    @Override
    public Result onlyFormatAttr(String coverImg, String originalPrice, String price) {
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        //表头
        header.add("图片");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPrice)){
            header.add("原价");
        }
        header.add("售价");
      //  header.add("库存");
      //  header.add("销量");
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        Map<String, Object> sku = new HashMap<>();
        sku.put("json", null);
        sku.put("detailJson", null);
        sku.put("skuImg", coverImg);
        sku.put("skuOriginalPrice", originalPrice);
        sku.put("skuPrice", price);
     //   sku.put("'%Y-%m-%d'", 999);
     //   sku.put("sales", 0);
        value.add(sku);
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data",map);
    }

    @Override
    public Result formatAttr(Long goodsId) {
        //1.获取商品规格值
        List<GoodsAttrValue> attr = goodsAttrValueService.findAllByGoodsId(goodsId);
        //sku集合
        List<GoodsSku> goodsSkuList = goodsSkuService.selectGoodsSkuByGoodsId(goodsId);
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        if (attrSize > 0){
            //4.循环规格值
            for (int i = 0; i < attrSize; i++) {
                //5.放入表头数据
                header.add(attr.get(i).getValue());
            }
        }
        header.add("图片");
        header.add("原价");
        header.add("售价");
     //   header.add("库存");
     //   header.add("销量");
        header.add("操作");
        //5.sku数据放入
        for (GoodsSku s : goodsSkuList) {
            Map<String, Object> sku = new HashMap<>();
            String detailJson = s.getDetailJson();
            if (detailJson != null){
                String[] split = detailJson.split(",");
                for (int i = 0; i < split.length; i++) {
                    sku.put("value"+i, split[i]);
                }
            }
            sku.put("detailJson", detailJson);
            sku.put("skuOriginalPrice", s.getSkuOriginalPrice());
            sku.put("skuPrice", s.getSkuPrice());
          //  sku.put("stock", s.getStock());
         //   sku.put("sales", s.getSales());
            sku.put("skuImg", s.getSkuImg());
            value.add(sku);
        }
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data",map);
    }

    @Override
    public Result findAttrValue(Long goodsId) {
        List<GoodsAttr> attrList = goodsAttrService.findAllByGoodsId(goodsId);
        GoodsAttr s = new GoodsAttr();
        if (attrList.size() > 0 && attrList != null){
            s = attrList.get(0);
            s.setAttrValue(goodsAttrValueService.findAllByGoodsId(goodsId));
        }
        return Result.success().put("data",s);
    }

    @Override
    public Result selectShortShop(double lng, double lat, String shopName, Integer page, Integer limit, Long shopId) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        IPage<GoodsShop> goodsShopIPage = goodsDao.selectShortShop(pages, lng, lat, shopName, shopId);
        CommonInfo one = commonInfoService.findOne(235);
        for(int i = 0;i<goodsShopIPage.getRecords().size();i++){
            String url="https://apis.map.qq.com/ws/geocoder/v1/";
            Map<String,String> maps=new HashMap<>();
            maps.put("location",goodsShopIPage.getRecords().get(i).getShopLat()+","+goodsShopIPage.getRecords().get(i).getShopLng());
            maps.put("key",one.getValue());
            String data = HttpClientUtil.doGet(url, maps);
            JSONObject jsonObject = JSON.parseObject(data);
            String status = jsonObject.getString("status");
            if("0".equals(status)){
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                String province = adInfo.get("province").toString();
                String city = adInfo.get("city").toString();
                String district = adInfo.get("district").toString();
                goodsShopIPage.getRecords().get(i).setProvince(province);
                goodsShopIPage.getRecords().get(i).setCity(city);
                goodsShopIPage.getRecords().get(i).setDistrict(district);
            }else{
                log.error("转换失败！！！原因:"+jsonObject.getString("message"));
            }
        }
        PageUtils pageUtils = new PageUtils(goodsShopIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAllShop(Integer page, Integer limit, String shopName) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectAllShop(pages, shopName));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAdminGoodsList(Integer page, Integer limit, Integer classifyId, String goodsName, Integer status, Long shopId, String shopName) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectAdminGoodsList(pages, classifyId, goodsName, status, shopId, shopName));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAllClassify(Integer page,Integer limit,String shopName, Long shopId) {
        if(page==null || limit==null){
            List<GoodsClassify> goodsClassifies = goodsDao.selectAllClassifyList(shopName, shopId);
            return Result.success().put("data", goodsClassifies);
        }else{
            Page<GoodsClassify> pages=new Page<>(page,limit);
            IPage<GoodsClassify> goodsClassifies = goodsDao.selectAllClassify(pages,shopName, shopId);
            return Result.success().put("data", goodsClassifies);
        }
    }

    @Override
    public Result shopAddGoods(Long shopId, List goodsIdList) {
        goodsDao.shopAddGoods(shopId, goodsIdList);
        return Result.success();
    }

    @Override
    public Result deleteGoodsById(Long goodsId) {
        goodsDao.delete(new QueryWrapper<Goods>().eq("goods_id", goodsId));
        goodsAttrService.deleteGoodsAttr(goodsId);
        return Result.success();
    }

    @Override
    public Result selectAllShopList(Long userId) {
        List<SysUserRoleEntity> sysUserRoleEntityList = sysUserRoleDao.selectList(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));
        List list = new ArrayList();
        for(int a = 0;a<sysUserRoleEntityList.size();a++){
            list.add(sysUserRoleEntityList.get(a).getRoleId());
        }
        if(list.size()==1&&list.contains(12L)){
            List<GoodsShop> goodsShops = goodsShopDao.selectListByAdmin(userId);
            return Result.success().put("data",goodsShops);
        }else {
            List<GoodsShop> goodsShops = goodsShopDao.selectList(null);
            return Result.success().put("data",goodsShops);
        }
    }

    @Override
    public Result selectShop(Integer page, Integer limit, Integer screen, Integer shopTypeId, Double lng, Double lat, String impotr) {
        //如果没有经纬度，则默认为北京的经纬度
        if(lng==null||lat==null||lng==0||lat==0){
//            lng = 108.8927;
//            lat = 34.2408;
            lng = 121.47;
            lat = 31.23;
        }
        Page<GoodsShop> pages = new Page<>(page, limit);
        CommonInfo one = commonInfoService.findOne(235);
        String url="https://apis.map.qq.com/ws/geocoder/v1/";
        Map<String,String> maps=new HashMap<>();
        maps.put("location",lat+","+lng);
        maps.put("key",one.getValue());
        String data = HttpClientUtil.doGet(url, maps);
        JSONObject jsonObject = JSON.parseObject(data);
        String status = jsonObject.getString("status");
        if("0".equals(status)){
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject adInfo = result.getJSONObject("ad_info");
            Object city = adInfo.get("city");
            IPage<GoodsShop> goodsShopIPage = goodsShopDao.selectShop(pages, screen, shopTypeId, lng, lat, String.valueOf(city), impotr);
            CommonInfo one1 = commonInfoService.findOne(292);
            CommonInfo one2 = commonInfoService.findOne(293);
            // 计算配送距离
            /*for(int i = 0;i<goodsShopIPage.getRecords().size();i++){
                Double distance = goodsShopIPage.getRecords().get(i).getDistance();
                Double errandTime = distance/Double.valueOf(one1.getValue());
                if(errandTime<Double.valueOf(one2.getValue())){
                    errandTime = Double.valueOf(one2.getValue());
                }
                goodsShopIPage.getRecords().get(i).setErrandTime(errandTime);
            }*/
            for(int a = 0;a<goodsShopIPage.getRecords().size();a++){
                Long shopId = goodsShopIPage.getRecords().get(a).getShopId();
                List<Goods> goodsListByGoodsName = goodsDao.selectGoodsBySalesAndGoodsName(shopId,impotr);
                List<Goods> goodsList;
                if(goodsListByGoodsName.size()>0){
                    goodsList=goodsListByGoodsName;
                    if(goodsListByGoodsName.size()!=3){
                        List<Goods> goodsLists = goodsDao.selectGoodsBySales(shopId);
                        if(goodsLists.size()>0){
                            for(int i=0;i<goodsLists.size();i++){
                                if(goodsListContains(goodsList,goodsLists.get(i))){
                                    goodsList.add(goodsLists.get(i));
                                }
                                if(goodsList.size()==3){
                                    break;
                                }
                            }
                        }
                    }
                }else{
                    goodsList = goodsDao.selectGoodsBySales(shopId);
                }

                goodsShopIPage.getRecords().get(a).setGoodsList(goodsList);
            }
            PageUtils pageUtils = new PageUtils(goodsShopIPage);
            return Result.success().put("data", pageUtils);
        }else{
            log.error("转换失败！！！原因:"+jsonObject.getString("message"));
        }
        return Result.error("获取定位失败！");
    }

    public boolean goodsListContains(List<Goods> goodsList,Goods goods){
        for(Goods goods1:goodsList){
            if(goods1.getGoodsId().equals(goods.getGoodsId())){
                return false;
            }
        }
        return true;
    }
    
    
    
    @Override
    public Result selectSearch(Integer page, Integer limit, String impotr, Double lng, Double lat) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        CommonInfo one = commonInfoService.findOne(235);
        String url="https://apis.map.qq.com/ws/geocoder/v1/";
        Map<String,String> maps=new HashMap<>();
        maps.put("location",lat+","+lng);
        maps.put("key",one.getValue());
        String data = HttpClientUtil.doGet(url, maps);
        JSONObject jsonObject = JSON.parseObject(data);
        String status = jsonObject.getString("status");
        if("0".equals(status)){
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject adInfo = result.getJSONObject("ad_info");
            Object city = adInfo.get("city");
            PageUtils pageUtils = new PageUtils(goodsShopDao.selectSearch(pages, impotr, lng, lat, String.valueOf(city)));
            return Result.success().put("data", pageUtils);
        }else{
            log.error("转换失败！！！原因:"+jsonObject.getString("message"));
        }
        return Result.error("获取定位失败！");

    }

    @Override
    public Result selectEvaluate(Integer page, Integer limit, Long shopId, Integer grade) {
        Page<Evaluate> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectEvaluate(pages, shopId, grade));
        int goodReputation = goodsShopDao.selectGoodReputation(shopId);
        int mediumReview = goodsShopDao.selectMediumReview(shopId);
        int negativeComment = goodsShopDao.selectNegativeComment(shopId);
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("pageUtils", pageUtils);
        hashMap.put("goodReputation", goodReputation);
        hashMap.put("mediumReview", mediumReview);
        hashMap.put("negativeComment", negativeComment);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectEvaluateByGoodsId(Long goodsId, Integer page, Integer limit) {
        Page<Evaluate> pages = new Page<>(page, limit);
        String goodsIds = ","+String.valueOf(goodsId)+",";
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectEvaluateByGoodsId(pages, goodsIds));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectGoodsById(Long goodsId) {
        Goods goods = goodsDao.selectGoodsById(goodsId);
        if(goods!=null){
            goods.setAttr(goodsAttrService.findByGoodsId(goodsId));
            goods.setSku(goodsSkuService.selectGoodsSkuByGoodsId(goodsId));
            return Result.success().put("data", goods);
        }
        return Result.success();
    }

    /*@Override
    public Result selectGoodsById(Long goodsId) {
        Goods goods = goodsDao.selectById(goodsId);
        List<GoodsSku> goodsSkuList = goodsSkuDao.selectList(new QueryWrapper<GoodsSku>().eq("goods_id", goodsId));
        List<GoodsSku> goodsSkus=new ArrayList<>();
        goodsSkus = setGoodsSkuList(goodsSkuList, goodsSkus, 0L);
        goods.setGoodsSkuList(goodsSkus);
        return Result.success().put("data", goods);
    }

    public List<GoodsSku> setGoodsSkuList(List<GoodsSku> goodsSkusList,List<GoodsSku> goodsSkus,Long parentId ){
        for(GoodsSku goodsSku:goodsSkusList){
            if(goodsSku.getParentId().equals(parentId)){
                goodsSkus.add(goodsSku);
                List<GoodsSku> goodsSkuList = goodsSku.getGoodsSkuList();
                if(goodsSkuList==null){
                    goodsSkuList=new ArrayList<>();
                }
                List<GoodsSku> goodsSkus1 = setGoodsSkuList(goodsSkusList, goodsSkuList, goodsSku.getSkuId());
                goodsSku.setGoodsSkuList(goodsSkus1);
            }
        }
        return goodsSkus;
    }*/


}
